package com.gthncz.hello.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.gthncz.hello.beans.RoledUser;
import com.gthncz.hello.mapper.RoledUserMapper;

@Service
public class RoledUserDetailService implements UserDetailsService {
	
	private static final Logger log = LoggerFactory.getLogger(RoledUserDetailService.class);
	
	public RoledUserDetailService() {
		log.info("RoledUserDetailService constructor.");
	}
	
	@Autowired
	private RoledUserMapper roleUserMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		log.warn("Entering loadUserByUsername " + username);
		RoledUser user = roleUserMapper.findByName(username);
		if(user == null) throw new UsernameNotFoundException("UserName "+ username + "Not Found!");
		else { // TODO 修改逻辑，密码存入数据的时候就
			/*
			PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
			String cryptPassword = passwordEncoder.encode(user.getPassword());
			log.info("Crypted Password: " + cryptPassword);
			user.setPassword(cryptPassword);
			*/
			log.info("loadUserByUsername get User: {}", user.toString());
			return user;
		}
	}
	
}
